class Solution(object):
    def equationsPossible(self, equations):
        edges = []
        no_edges = []
        p = [i for i in range(26)]
        for eq in equations:
            x = ord(eq[0]) - ord('a')
            y = ord(eq[3]) - ord('a')
            if eq[1] == '=':
                edges.append([x, y])
            if eq[1] == '!':
                no_edges.append([x, y])

        def find(x):
            if x == p[x]:
                return x
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rootx = find(x)
            rooty = find(y)
            if rootx != rooty:
                if rootx > rooty:
                    p[rootx] = rooty
                else:
                    p[rooty] = rootx

        for pair in edges:
            union(pair[0], pair[1])

        for pair in no_edges:
            rootx = find(pair[0])
            rooty = find(pair[1])
            if rootx == rooty:
                return False
        return True


data = Solution()
equations = ["a==b", "b!=a"]
print(data.equationsPossible(equations))
